<template>
  <div class="container">
    <button @click="closeCamera" class="btn">close</button>
    <div id="reader"></div>
  </div>
</template>

<script setup>
/* eslint-disable */
import { onMounted } from "vue";
import { useRouter } from "vue-router";
import { showDialog, showToast } from "vant";

import { Html5Qrcode } from "html5-qrcode";

import { routeQuery } from "@/hook/routerHandle.js";
import { OpenChildrenPage } from "@/hook/routerHandle";

import { verifyQrcode } from "@/server/api/profile";
import { useIndexStore } from "@/stores/indexStore";
import { useI18n } from "vue-i18n";
import { ref } from "vue"
const { t } = useI18n();

const useStore = useIndexStore();
const router = useRouter();
let { flag } = routeQuery();
let html5QrCode = null;

// console.log("flag:", flag);

onMounted(() => {
  html5QrCode = new Html5Qrcode("reader");
});

/* const getImg = (e) => {
  console.log("e.target.file", e.target.files[0]);

  if (e.target.files.length == 0) return;

  const imageFile = e.target.files[0];

  html5QrCode
    .scanFile(imageFile, true)
    .then((decodedText) => {
      result.value = decodedText;
    })
    .catch((err) => {
      result.value = "扫码失败:\n" + err;
    });
}; */

const closeCamera = () => {
  router.back();
  closeScan();
};

if (flag) {
  Html5Qrcode.getCameras()
    .then((devices) => {
      /**
       * devices would be an array of objects of type:
       * { id: "id", label: "label" }
       */
      if (devices && devices.length) {
        var cameraId = "";
        if (devices.length == 1) {
          cameraId = devices[0].id;
        }
        if (devices.length == 2) {
          cameraId = devices[1].id;
        }
        if (cameraId) {
          console.log("获取摄像头成功11");
          console.log(cameraId);
          startScan(cameraId);
        }

        // .. use this to start scanning.
      } else {
        startWithoutCameraId();
      }
    })
    .catch((err) => {
      showToast(t("Qrcode.message"));
    });
}

const startScan = (cameraId) => {
  html5QrCode
    .start(
      cameraId,
      {
        fps: 10, // Optional, frame per seconds for qr code scanning
        qrbox: { width: 280, height: 400 }, // Optional, if you want bounded box UI
      },
      async (decodedText, decodedResult) => {
        // do something when code is read
        console.log("result", decodedText);

        // const regex = /\/\/(.+)/;
        // const result = decodedText.match(regex)[1];
        // let res = await verifyQrcode(result);
        // let result = null;
        // result = decodedText;
        // let res = await verifyQrcode(result);
        const qrcode = ref({})
        qrcode.value = decodedText;
        let res = await verifyQrcode(qrcode.value);


        useStore.merchantData = res.data;
        console.log(res);
        if (res.data.data) {
          console.log("guogguggo");
          closeScan();
          OpenChildrenPage("/paymentView", res.data.data);
        } else {
          showDialog({ message: t("Qrcode.tip") }).then(() => {
            closeScan();
            OpenChildrenPage("/MeView");
          });
        }
      },
      (errorMessage) => {
        // showToast('扫码失败');
        // parse error, ignore it.
        // console.log("errorMesage:", errorMessage);
      }
    )
    .catch((err) => {
      // Start failed, handle it.
      console.log("未能获取摄像头");
    });
};

const closeScan = () => {
  html5QrCode
    .stop()
    .then((ignore) => {
      // QR Code scanning is stopped.
      showToast(t("Qrcode.tip2"));
    })
    .catch((err) => {
      // Stop failed, handle it.
    });
};

function startWithoutCameraId() {
  //environment 表示后置摄像头  换成user则表示前置摄像头
  html5QrCode.start(
    { facingMode: "user" } || {
      facingMode: { exact: "user" },
    },
    {
      fps: 10, // Optional, frame per seconds for qr code scanning
      qrbox: { width: 280, height: 400 }, // Optional, if you want bounded box UI
    },
    (decodedText, decodedResult) => {
      // do something when code is read
    },
    (errorMessage) => {
      // parse error, ignore it.
    }
  );
}
</script>

<style lang="css" scoped>
.container {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #999;
}

button {
  display: block;
  width: 80vw;
  height: 40rem;
  line-height: 40rem;
  color: #fff;
  text-align: center;
  margin-bottom: 20rem;
  border-radius: 4rem;
  border: none;
  background-color: #26a2ff;
  cursor: pointer;
}

#upload-input {
  opacity: 0;
  filter: alpha(opacity=0);
  display: inline-block;
  width: 100%;
  height: 100%;
}

.upload-text {
  position: relative;
  bottom: 40rem;
  user-select: none;
}

#reader {
  width: 100vw;
  height: 50vh;
}

.btn {
  position: absolute;
  bottom: -10rem;
  z-index: 999;
  font-size: 18rem;
}
</style>
